package cn.linkai.star.graph.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.linkai.star.graph.core.mapper.UserMapper;
import cn.linkai.star.graph.core.pojo.User;
import cn.linkai.star.graph.core.dto.request.UserLoginReqDTO;
import cn.linkai.star.graph.core.dto.respone.UserLoginResDTO;
import cn.linkai.star.graph.core.service.UserService;
import cn.linkai.star.graph.core.utils.JWTUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.coyote.BadRequestException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 登录
     * @param userLoginReqDTO
     * @return
     */
    @Override
    public UserLoginResDTO loginByPassword(UserLoginReqDTO userLoginReqDTO) throws BadRequestException {
        //参数校验
        if(userLoginReqDTO == null ||
                userLoginReqDTO.getUsername () == null ||
                userLoginReqDTO.getPassword() == null){
            throw new BadRequestException ("账号和密码不能为空");
        }
        //根据用户名或手机查询用户
        User user =  lambdaQuery ()
                .or(c -> c.eq(User::getUsername,userLoginReqDTO.getUsername ()))
                .or(c -> c.eq(User::getMobile,userLoginReqDTO.getUsername ()))
                .one ();

        //校验密码
        if(user == null || !BCrypt.checkpw (userLoginReqDTO.getPassword(), user.getPassword())){
            throw new BadRequestException ("用户名或密码错误");
        }

        //生成token，封装返回
        return generateLoginInfo(user);
    }

    private UserLoginResDTO generateLoginInfo(User user) {
        //拷贝数据
        UserLoginResDTO loginResDTO = BeanUtil.toBean (user, UserLoginResDTO.class);
        //设置姓名，username mobile
        if(StrUtil.isEmpty(loginResDTO.getName())){
            loginResDTO.setName(user.getUsername());
        }
        if(StrUtil.isEmpty(loginResDTO.getName())){
            loginResDTO.setName(user.getMobile());
        }
        //设置token
        String token = JWTUtils.createJWT (user.getId (), loginResDTO.getName ());
        loginResDTO.setToken (token);
        return loginResDTO;
    }
}
